import type { MenuProps } from 'antd'

export function extractAllKeys(menuItems: MenuProps['items'] = []): string[] {
    let keys: string[] = []
    menuItems.forEach(item => {
        if (!item) return
        if ('key' in item && typeof item.key === 'string') {
            keys.push(item.key)
        }
        if ('children' in item && Array.isArray(item.children)) {
            keys = keys.concat(extractAllKeys(item.children))
        }
    })
    return keys
}

export function createKeyParentMap(
    menuItems: MenuProps['items'],
    parent: string | null = null,
    map: Record<string, string> = {}
): Record<string, string> {
    menuItems?.forEach(item => {
        if (!item) return
        if ('key' in item && typeof item.key === 'string') {
            if (parent) {
                map[item.key] = parent
            }
            if ('children' in item && Array.isArray(item.children)) {
                createKeyParentMap(item.children, item.key, map)
            }
        }
    })
    return map
}

export function findMatchedKey(pathname: string, keys: string[]): string {
    const sorted = keys
        .filter(k => pathname.startsWith(k))
        .sort((a, b) => b.length - a.length)
    return sorted[0] || ''
}
